home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / lisp / wcl-21.lha / wcl-2.1 / src / cl / pprint / pprint-doc.text < prev    next >
Lisp/Scheme  |  1992-09-10  |  50KB  |  1,029 lines

  1.  
  2. ;------------------------------------------------------------------------
  3.  
  4. ;Copyright 1989 by the Massachusetts Institute of Technology, Cambridge, 
  5. ;Massachusetts.
  6.  
  7. ;Permission to use, copy, modify, and distribute this software and its
  8. ;documentation for any purpose and without fee is hereby granted,
  9. ;provided that this copyright and permission notice appear in all
  10. ;copies and supporting documentation, and that the name of M.I.T. not
  11. ;be used in advertising or publicity pertaining to distribution of the
  12. ;software without specific, written prior permission. M.I.T. makes no
  13. ;representations about the suitability of this software for any
  14. ;purpose.  It is provided "as is" without express or implied warranty.
  15.  
  16. ;    M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  17. ;    ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
  18. ;    M.I.T. BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  19. ;    ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  20. ;    WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
  21. ;    ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  22. ;    SOFTWARE.
  23.  
  24. ;------------------------------------------------------------------------
  25.  
  26.  
  27.               Pretty Printing using XP
  28.  
  29.               Richard C. Waters
  30.  
  31.  
  32. Pretty printing has traditionally been a black box process, displaying
  33. program code using a set of fixed layout rules.  Its utility can be greatly
  34. enhanced by opening it up to user control.
  35.  
  36. By providing direct access to the mechanisms within the pretty printer that
  37. make dynamic decisions about layout, the macros and functions
  38. PPRINT-LOGICAL-BLOCK, PPRINT-NEWLINE, and PPRINT-INDENT make it possible to
  39. specify pretty printing layout rules as a part of any function that
  40. produces output.  They also make it very easy for the detection of
  41. circularity and sharing, and abbreviation based on length and nesting depth
  42. to be supported by the function.  The function SET-PPRINT-DISPATCH makes it
  43. possible to associate a user-defined pretty printing function with any type
  44. of object.  Together, these facilities enable users to redefine the way
  45. code is displayed and allow the full power of pretty printing to be applied
  46. to complex combinations of data structures.
  47.  
  48.           Pretty Printing Control Variables
  49.  
  50. *PRINT-RIGHT-MARGIN*                                             [variable]
  51.  
  52. A primary goal of pretty printing is to keep the output between a pair of
  53. margins.  The left margin is set at the column where the output begins.  If
  54. this cannot be determined, the left margin is set to zero.
  55.  
  56. When *PRINT-RIGHT-MARGIN* is not NIL, it specifies the right margin to use
  57. when making layout decisions.  When *PRINT-RIGHT-MARGIN* is NIL (the
  58. initial value), the right margin is set at the maximum line length that can
  59. be displayed by the output stream without wraparound or truncation.  If
  60. this cannot be determined, the right margin is set to an implementation
  61. dependent value.
  62.  
  63. To allow for the possibility of variable-width fonts, *PRINT-RIGHT-MARGIN*
  64. is interpreted in terms of ems---the length of an "m" in the font being
  65. used to display characters on the relevant output stream at the moment when
  66. the variables are consulted.
  67.  
  68. *PRINT-MISER-WIDTH*                                              [variable]
  69.  
  70. If *PRINT-MISER-WIDTH* is not NIL, the pretty printer switches to a compact
  71. style of output (called miser style) whenever the width available for
  72. printing a substructure is less than or equal to *PRINT-MISER-WIDTH* ems.
  73. The initial value of *PRINT-MISER-WIDTH* is implementation-dependent.
  74.  
  75. *PRINT-LINES*                                                    [variable]
  76.  
  77. When given a value other than its initial value of NIL, *PRINT-LINES*
  78. limits the number of output lines produced when something is pretty
  79. printed.  If an attempt is made to go beyond *PRINT-LINES* lines, "
  80. .." is printed at the end of the last line followed by all of the
  81. suffixes (closing delimiters) that are pending to be printed.
  82.  
  83. (let ((*print-right-margin* 25) (*print-lines* 3))
  84.   (pprint '(progn (setq a 1 b 2 c 3 d 4))))
  85.  
  86. (PROGN (SETQ A 1
  87.              B 2
  88.              C 3 ..))
  89.  
  90. (The symbol ".." is printed out to ensure that a reader error will occur
  91. if the output is later read.  A symbol different than "..." is used to
  92. indicate that a different kind of abbreviation has occurred.)
  93.  
  94. *PRINT-PPRINT-DISPATCH*                                          [variable]
  95.  
  96. When *PRINT-PRETTY* is not NIL, printing is controlled by the `pprint
  97. dispatch table' stored in the variable *PRINT-PPRINT-DISPATCH*.  The
  98. initial value of *PRINT-PPRINT-DISPATCH* is implementation dependent and
  99. causes traditional pretty printing of Lisp code.  The last section of this
  100. proposal explains how the contents of this table can be changed.
  101.  
  102.  
  103. The function WRITE accepts keyword arguments :PPRINT-DISPATCH,
  104. :RIGHT-MARGIN, :LINES, and :MISER-WIDTH corresponding to
  105. *PRINT-PPRINT-DISPATCH*, *PRINT-RIGHT-MARGIN*, *PRINT-LINES*, and
  106. *PRINT-MISER-WIDTH*.
  107.  
  108.  
  109.          Dynamic Control of the Arrangement of Output
  110.  
  111. The following functions and macros support precise control of what should
  112. be done when a piece of output is too large to fit in the space available.
  113. Three concepts underlie the way these operations work---`logical blocks',
  114. `conditional newlines', and `sections'.  Before proceeding further, it is
  115. important to define these terms.
  116.  
  117. The first line of Figure 1 shows a schematic piece of output.  The
  118. characters in the output are represented by "-"s.  The positions of
  119. conditional newlines are indicated by digits.  The beginnings and ends of
  120. logical blocks are indicated by "<" and ">" respectively.
  121.  
  122. The output as a whole is a logical block and the outermost section.  This
  123. section is indicated by the 0's on the second line of Figure 1.  Logical
  124. blocks nested within the output are specified by the macro
  125. PPRINT-LOGICAL-BLOCK.  Conditional newline positions are specified by calls
  126. on PPRINT-NEWLINE.  Each conditional newline defines two sections (one
  127. before it and one after it) and is associated with a third (the section
  128. immediately containing it).
  129.  
  130. The section after a conditional newline consists of: all the output up to,
  131. but not including, (a) the next conditional newline immediately contained
  132. in the same logical block; or if (a) is not applicable, (b) the next
  133. newline that is at a lesser level of nesting in logical blocks; or if (b)
  134. is not applicable, (c) the end of the output.
  135.  
  136. The section before a conditional newline consists of: all the output back
  137. to, but not including, (a) the previous conditional newline that is
  138. immediately contained in the same logical block; or if (a) is not
  139. applicable, (b) the beginning of the immediately containing logical block.
  140. The last four lines in Figure 1 indicate the sections before and after the
  141. four conditional newlines.
  142.  
  143. The section immediately containing a conditional newline is the shortest
  144. section that contains the conditional newline in question.  In Figure 1,
  145. the first conditional newline is immediately contained in the section
  146. marked with 0's, the second and third conditional newlines are immediately
  147. contained in the section before the fourth conditional newline, and the
  148. fourth conditional newline is immediately contained in the section after
  149. the first conditional newline.
  150.  
  151.  
  152.                  <-1---<--<--2---3->--4-->->
  153.                  000000000000000000000000000
  154.                  11 111111111111111111111111
  155.                            22 222
  156.                               333 3333
  157.                         44444444444444 44444
  158.  
  159. Figure 1: Example of logical blocks, conditional newlines, and sections.
  160.  
  161. Whenever possible, the pretty printer displays the entire contents of a
  162. section on a single line.  However, if the section is too long to fit in
  163. the space available, line breaks are inserted at conditional newline
  164. positions within the section.
  165.  
  166.  
  167. PPRINT-NEWLINE kind &OPTIONAL (stream *STANDARD-OUTPUT*)    [Function]
  168.  
  169. STREAM (which defaults to *STANDARD-OUTPUT*) follows the standard
  170. conventions for stream arguments to printing functions (i.e., NIL stands
  171. for *STANDARD-OUTPUT* and T stands for *TERMINAL-IO*).  The KIND argument
  172. specifies the style of conditional newline.  It must be one of :LINEAR,
  173. :FILL, :MISER, or :MANDATORY.  An error is signalled if any other value is
  174. supplied.  If STREAM is a pretty printing stream created by
  175. PPRINT-LOGICAL-BLOCK, a line break is inserted in the output when the
  176. appropriate condition below is satisfied.  Otherwise, PPRINT-NEWLINE has no
  177. effect.  The value NIL is always returned.
  178.  
  179. If KIND is :LINEAR, it specifies a `linear-style' conditional newline.  A
  180. line break is inserted if and only if the immediately containing section
  181. cannot be printed on one line.  The effect of this is that line breaks are
  182. either inserted at every linear-style conditional newline in a logical
  183. block or at none of them.
  184.  
  185. If KIND is :MISER, it specifies a `miser-style' conditional newline.  A
  186. line break is inserted if and only if the immediately containing section
  187. cannot be printed on one line and miser style is in effect in the
  188. immediately containing logical block.  The effect of this is that
  189. miser-style conditional newlines act like linear-style conditional
  190. newlines, but only when miser style is in effect.  Miser style is in effect
  191. for a logical block if and only if the starting position of the logical
  192. block is less than or equal to *PRINT-MISER-WIDTH* from the right margin.
  193.  
  194. If KIND is :FILL, it specifies a `fill-style' conditional newline.  A line
  195. break is inserted if and only if either (a) the following section cannot be
  196. printed on the end of the current line, (b) the preceding section was not
  197. printed on a single line, or (c) the immediately containing section cannot
  198. be printed on one line and miser style is in effect in the immediately
  199. containing logical block.  If a logical block is broken up into a number of
  200. subsections by fill-style conditional newlines, the basic effect is that
  201. the logical block is printed with as many subsections as possible on each
  202. line.  However, if miser style is in effect, fill-style conditional
  203. newlines act like linear-style conditional newlines.
  204.  
  205. If KIND is :MANDATORY, it specifies a `mandatory-style' conditional
  206. newline.  A line break is always inserted.  This implies that none of the
  207. containing sections can be printed on a single line and will therefore
  208. trigger the insertion of line breaks at linear-style conditional newlines
  209. in these sections.
  210.  
  211. When a line break is inserted by any type of conditional newline, any
  212. blanks that immediately precede the conditional newline are omitted from
  213. the output and indentation is introduced at the beginning of the next line.
  214. By default, the indentation causes the following line to begin in the same
  215. horizontal position as the first character in the immediately containing
  216. logical block.  (The indentation can be changed via PPRINT-INDENT.)
  217.  
  218. There are a variety of ways unconditional newlines can be introduced into
  219. the output (e.g., via TERPRI or by printing a string containing a newline
  220. character).  As with mandatory conditional newlines, this prevents any of
  221. the containing sections from being printed on one line.  In general, when
  222. an unconditional newline is encountered, it is printed out without
  223. suppression of the preceding blanks and without any indentation following
  224. it.  However, if a per-line prefix has been specified (see
  225. PPRINT-LOGICAL-BLOCK), this prefix will always be printed no matter how a
  226. newline originates.
  227.  
  228.  
  229. PPRINT-LOGICAL-BLOCK (stream-symbol list                     [Macro]
  230.                       &KEY :prefix :per-line-prefix :suffix)
  231.                      &BODY body
  232.  
  233. This macro causes printing to be grouped into a logical block.  The value
  234. NIL is always returned.
  235.  
  236. STREAM-SYMBOL must be a symbol.  If it is NIL, it is treated the same as
  237. if it were *STANDARD-OUTPUT*.  If it is T, it is treated the same as if
  238. it were *TERMINAL-IO*.  The run-time value of STREAM-SYMBOL must be a
  239. stream (or NIL standing for *STANDARD-OUTPUT* or T standing for *TERMINAL-IO*).
  240. The logical block is printed into this destination stream.
  241.  
  242. The BODY can contain any arbitrary Lisp forms.  Within the BODY,
  243. STREAM-SYMBOL (or *STANDARD-OUTPUT* if STREAM-SYMBOL is NIL, or
  244. *TERMINAL-IO* if STREAM-SYMBOL is T) is bound to a `pretty printing' stream
  245. that supports decisions about the arrangement of output and then forwards
  246. the output to the destination stream.  All the standard printing functions
  247. (e.g., WRITE, PRINC, TERPRI) can be used to print output the pretty
  248. printing stream created by PPRINT-LOGICAL-BLOCK.  All and only the output
  249. sent to this pretty printing stream is treated as being in the logical
  250. block.
  251.  
  252. PPRINT-LOGICAL-BLOCK and the pretty printing stream it creates have dynamic
  253. extent.  It is undefined what happens if output is attempted outside of
  254. this extent to the pretty printing stream created.  It is unspecified what
  255. happens if, within this extent, any output is sent directly to the
  256. underlying destination stream.
  257.  
  258. The :SUFFIX, :PREFIX, and :PER-LINE-PREFIX must all be expressions that (at
  259. run time) evaluate to strings.  :SUFFIX (which defaults to the null string)
  260. specifies a suffix that is printed just after the logical block.  The
  261. :PREFIX and :PRE-LINE-PREFIX arguments are mutually exclusive.  If neither
  262. :PREFIX or :PER-LINE-PREFIX is specified, a :PREFIX of the null string is
  263. assumed.  :PREFIX specifies a prefix to be printed before the beginning of
  264. the logical block.  :PER-LINE-PREFIX specifies a prefix that is printed
  265. before the block and at the beginning of each new line in the block.  An
  266. error is signalled if :PREFIX and :PRE-LINE-PREFIX are both used or if the
  267. :SUFFIX, :PREFIX, or :PER-LINE-PREFIX do not evaluate to strings.
  268.  
  269. LIST is interpreted as being a list that BODY is responsible for
  270. printing.  (See PPRINT-EXIT-IF-LIST-EXHAUSTED and PPRINT-POP.)  If
  271. LIST does not (at run time) evaluate to a list, it is printed using
  272. WRITE.  (This makes it easier to write printing functions that are
  273. robust in the face of malformed arguments.)  If *PRINT-CIRCLE* (and
  274. possibly *PRINT-SHARED*) is not NIL and LIST is a circular (or shared)
  275. reference to a cons, then an appropriate #n# marker is printed.  (This
  276. makes it easy to write printing functions that provide full support
  277. for circularity and sharing abbreviation.)  If *PRINT-LEVEL* is not
  278. NIL and the logical block is at a dynamic nesting depth of greater
  279. than *PRINT-LEVEL* in logical blocks, # is printed.  (This makes easy
  280. to write printing functions that provide full support for depth
  281. abbreviation.)
  282.  
  283. If either of the three conditions above occurs, the indicated output is
  284. printed on STREAM-SYMBOL and the BODY is skipped along with the printing of
  285. the :PREFIX and :SUFFIX.  (If the BODY is not responsible for printing a
  286. list, then the first two tests above can be turned off by supplying NIL for
  287. the LIST argument.)
  288.  
  289. In addition to the LIST argument of PPRINT-LOGICAL-BLOCK, the arguments of
  290. the standard printing functions such as WRITE, PRINT, PPRINT, PRINT1, and
  291. PPRINT, as well as the arguments of the standard FORMAT directives such as
  292. ~A, ~S, (and ~W) are all checked (when necessary) for circularity and
  293. sharing.  However, such checking is not applied to the arguments of the
  294. functions WRITE-LINE, WRITE-STRING, and WRITE-CHAR or to the literal text
  295. output by FORMAT.  A consequence of this is that you must use one of the
  296. latter functions if you want to print some literal text in the output that
  297. is not supposed to be checked for circularity or sharing.  (See the
  298. examples below.)
  299.  
  300. ----------------------------------------
  301.  
  302. Implementation note:  detection of circularity and sharing is supported by
  303. the pretty printer by in essence performing requested output twice.
  304. On the first pass, circularities and sharing are detected and the
  305. actual outputting of characters is suppressed.  On the second pass, the
  306. appropriate #n= and #n# markers are inserted and characters are output.
  307.  
  308. A consequence of this two-pass approach to the detection of circularity and
  309. sharing is that the BODY of a PPRINT-LOGICAL-BLOCK must not perform any
  310. side-effects on the surrounding environment.  This includes not modifying
  311. any variables that are bound outside of its scope.  Obeying this
  312. restriction is facilitated by using PPRINT-POP, instead of an ordinary POP
  313. when traversing a list being printed by the BODY of a
  314. PPRINT-LOGICAL-BLOCK.)
  315.  
  316. ----------------------------------------
  317.  
  318.  
  319. PPRINT-EXIT-IF-LIST-EXHAUSTED                                       [Macro]  
  320.  
  321. PPRINT-EXIT-IF-LIST-EXHAUSTED tests whether or not the LIST passed to
  322. PPRINT-LOGICAL-BLOCK has been exhausted (see PPRINT-POP).  If this list has
  323. been reduced to NIL, PPRINT-EXIT-IF-LIST-EXHAUSTED terminates the execution
  324. of the immediately containing PPRINT-LOGICAL-BLOCK except for the printing
  325. of the suffix.  Otherwise PPRINT-EXIT-IF-LIST-EXHAUSTED returns NIL.  An
  326. error message is issued if PPRINT-EXIT-IF-LIST-EXHAUSTED is used anywhere
  327. other than syntactically nested within a call on PPRINT-LOGICAL-BLOCK.  It
  328. is undefined what happens if PPRINT-POP is executed outside of the dynamic
  329. extent of this PPRINT-LOGICAL-BLOCK.
  330.  
  331.  
  332. PPRINT-POP                                                          [Macro]  
  333.  
  334. PPRINT-POP pops elements one at a time off the LIST passed to
  335. PPRINT-LOGICAL-BLOCK obeying *PRINT-LENGTH*, *PRINT-CIRCLE*, and
  336. *PRINT-SHARED*.  An error message is issued if it is used anywhere
  337. other than syntactically nested within a call on PPRINT-LOGICAL-BLOCK.
  338. It is undefined what happens if PPRINT-POP is executed outside of the
  339. dynamic extent of this PPRINT-LOGICAL-BLOCK.
  340.  
  341. Each time PPRINT-POP is called, it pops the next value off the LIST
  342. passed to PPRINT-LOGICAL-BLOCK and returns it.  However, before doing
  343. this, it performs three tests.  If the remaining list is not a list
  344. (i.e., a cons or NIL), ". " is printed followed by the remaining list.
  345. (This makes it easier to write printing functions that are robust in
  346. the face of malformed arguments.)  If *PRINT-LENGTH* is NIL and
  347. PPRINT-POP has already been called *PRINT-LENGTH* times within the
  348. immediately containing logical block, "..." is printed.  (This makes
  349. it easy to write printing functions that properly handle
  350. *PRINT-LENGTH*.)  If *PRINT-CIRCLE* (and possibly *PRINT-SHARED*) is
  351. not NIL, and the remaining list is a circular (or shared) reference,
  352. then ". " is printed followed by an appropriate #n# marker.  (This
  353. catches instances of cdr circularity and sharing in lists.)
  354.  
  355. If either of the three conditions above occurs, the indicated output is
  356. printed on the pretty printing stream created by the immediately containing
  357. PPRINT-LOGICAL-BLOCK and the execution of the immediately containing
  358. PPRINT-LOGICAL-BLOCK is terminated except for the printing of the suffix.
  359.  
  360. If PPRINT-LOGICAL-BLOCK is given a LIST argument of NIL---because it is not
  361. processing a list---PPRINT-POP can still be used to obtain support for
  362. *PRINT-LENGTH* (see the example function PPRINT-VECTOR below).  In this
  363. situation, the first and third tests above are disabled and
  364. PPRINT-POP always returns NIL.
  365.  
  366.  
  367. PPRINT-INDENT relative-to n &OPTIONAL (stream *STANDARD-OUTPUT*) [Function]
  368.  
  369. PPRINT-INDENT specifies the indentation to use in a logical block.  STREAM
  370. (which defaults to *STANDARD-OUTPUT*) follows the standard conventions for
  371. stream arguments to printing functions.  N specifies the indentation in
  372. ems.  If RELATIVE-TO is :BLOCK, the indentation is set to the horizontal
  373. position of the first character in the block plus N ems.  If RELATIVE-TO is
  374. :CURRENT, the indentation is set to the current output position plus N ems.
  375. (For robustness in the face of variable-width fonts, it is advisable to use
  376. :CURRENT with an N of zero whenever possible.)
  377.  
  378. N can be negative; however, the total indentation cannot be moved left of
  379. the beginning of the line or left of the end of the rightmost per-line
  380. prefix.  Changes in indentation caused by PPRINT-INDENT do not take
  381. effect until after the next line break.  In addition, in miser mode all
  382. calls on PPRINT-INDENT are ignored, forcing the lines corresponding to the
  383. logical block to line up under the first character in the block.
  384.  
  385. An error is signalled if a value other than :BLOCK or :CURRENT is supplied
  386. for RELATIVE-TO.  If STREAM is a pretty printing stream created by
  387. PPRINT-LOGICAL-BLOCK, PPRINT-INDENT sets the indentation in the innermost
  388. dynamically enclosing logical block.  Otherwise, PPRINT-INDENT has no
  389. effect.  The value NIL is always returned.
  390.  
  391.  
  392. PPRINT-TAB kind colnum colinc &OPTIONAL (stream *STANDARD-OUTPUT*) [function]
  393.  
  394. PPRINT-TAB specifies tabbing as performed by the standard FORMAT directive
  395. ~T.  STREAM (which defaults to *STANDARD-OUTPUT*) follows the standard
  396. conventions for stream arguments to printing functions.  The arguments
  397. COLNUM and COLINC correspond to the two parameters to ~T and are in terms
  398. of ems.  The KIND argument specifies the style of tabbing.  It must be one
  399. of :LINE (tab as by ~T) :SECTION (tab as by ~T, but measuring horizontal
  400. positions relative to the start of the dynamically enclosing section),
  401. :LINE-RELATIVE (tab as by ~@T), or :SECTION-RELATIVE (tab as by ~@T, but
  402. measuring horizontal positions relative to the start of the dynamically
  403. enclosing section).  An error is signalled if any other value is supplied
  404. for KIND.  If STREAM is a pretty printing stream created by
  405. PPRINT-LOGICAL-BLOCK, tabbing is performed.  Otherwise, PPRINT-TAB has no
  406. effect.  The value NIL is always returned.
  407.  
  408.  
  409. PPRINT-FILL STREAM LIST &OPTIONAL (COLON? T) ATSIGN?                 [function]
  410. PPRINT-LINEAR STREAM LIST &OPTIONAL (COLON? T) ATSIGN?               [function]
  411. PPRINT-TABULAR STREAM LIST &OPTIONAL (COLON? T) ATSIGN? (TABSIZE 16) [function]
  412.  
  413. These three functions specify particular ways of pretty printing lists.
  414. STREAM follows the standard conventions for stream arguments to printing
  415. functions.  Each function prints parentheses around the output if and only
  416. if COLON? (default T) is not NIL.  Each function ignores its ATSIGN?
  417. argument and returns NIL.  (These two arguments are included in this way so
  418. that these functions can be used via ~/.../ and as SET-PPRINT-DISPATCH
  419. functions as well as directly.)  Each function handles abbreviation and the
  420. detection of circularity and sharing correctly, and uses WRITE to print
  421. LIST when given a non-list argument.
  422.  
  423. The function PPRINT-LINEAR prints a list either all on one line, or with
  424. each element on a separate line.  The function PPRINT-FILL prints a list
  425. with as many elements as possible on each line.  The function
  426. PPRINT-TABULAR is the same as PPRINT-FILL except that it prints the
  427. elements so that they line up in columns.  This function takes an
  428. additional argument TABSIZE (default 16) that specifies the column
  429. spacing in ems.
  430.  
  431. ---
  432.  
  433. As an example of the interaction of logical blocks, conditional newlines,
  434. and indentation, consider the function SIMPLE-PPRINT-DEFUN below.  This
  435. function prints out lists whose cars are DEFUN in the standard way assuming
  436. that the list has exactly length 4.
  437.  
  438. (defun simple-pprint-defun (*standard-output* list)
  439.   (pprint-logical-block (*standard-output* list :prefix "(" :suffix ")")
  440.     (write (first list))
  441.     (write-char #\space)
  442.     (pprint-newline :miser)
  443.     (pprint-indent :current 0)
  444.     (write (second list))
  445.     (write-char #\space)
  446.     (pprint-newline :fill)
  447.     (write (third list))
  448.     (pprint-indent :block 1)
  449.     (write-char #\space)
  450.     (pprint-newline :linear)
  451.     (write (fourth list))))
  452.  
  453. Suppose that one evaluates the following:
  454.  
  455. (simple-pprint-defun *standard-output* '(defun prod (x y) (* x y)))
  456.  
  457. If the line width available is greater than or equal to 26, then all of the
  458. output appears on one line.  If the line width available is reduced to 25,
  459. a line break is inserted at the linear-style conditional newline before the
  460. expression (* X Y), producing the output shown.  The (PPRINT-INDENT :BLOCK 1)
  461. causes (* X Y) to be printed at a relative indentation of 1 in the logical block.
  462.  
  463. (DEFUN PROD (X Y) 
  464.   (* X Y))
  465.  
  466. If the line width available is 15, a line break is also inserted at the
  467. fill style conditional newline before the argument list.  The call on
  468. (PPRINT-INDENT :CURRENT 0) causes the argument list to line up under the
  469. function name.
  470.  
  471. (DEFUN PROD
  472.        (X Y)
  473.   (* X Y))
  474.  
  475. If *PRINT-MISER-WIDTH* were greater than or equal to 14, the example output
  476. above would have been as follows, because all indentation changes are
  477. ignored in miser mode and line breaks are inserted at miser-style
  478. conditional newlines.
  479.  
  480. (DEFUN
  481.  PROD
  482.  (X Y)
  483.  (* X Y))
  484.  
  485. ---
  486.  
  487. As an example of a per-line prefix, consider that evaluating the following
  488. produces the output shown with a line width of 20 and *PRINT-MISER-WIDTH*
  489. of NIL.
  490.  
  491. (pprint-logical-block (*standard-output* nil :per-line-prefix ";;; ")
  492.   (simple-pprint-defun *standard-output* '(defun prod (x y) (* x y))))
  493.  
  494. ;;; (DEFUN PROD
  495. ;;;        (X Y)
  496. ;;;   (* X Y))
  497.  
  498. ---
  499.  
  500. As a more complex (and realistic) example, consider the function PPRINT-LET
  501. below.  This specifies how to print a LET in the standard style.  It is more
  502. complex than the example above, because it has to deal with nested structure.
  503. Also, unlike the example above it contains complete code to readably print any
  504. possible list that begins with the symbol LET.  The outermost
  505. PPRINT-LOGICAL-BLOCK handles the printing of the input list as a whole and
  506. specifies that parentheses should be printed in the output.  The second
  507. PPRINT-LOGICAL-BLOCK handles the list of binding pairs.  Each pair in the list
  508. is itself printed by the innermost PPRINT-LOGICAL-BLOCK.  (A LOOP is used
  509. instead of merely decomposing the pair into two elements so that readable
  510. output will be produced no matter whether the list corresponding to the pair
  511. has one element, two elements, or (being malformed) has more than two
  512. elements.)   A space and a fill-style conditional newline are placed after
  513. each pair except the last.  The loop at the end of the topmost
  514. PPRINT-LOGICAL-BLOCK prints out the forms in the body of the LET separated by
  515. spaces and linear-style conditional newlines.
  516.  
  517. (defun pprint-let (*standard-output* list)
  518.   (pprint-logical-block (nil list :prefix "(" :suffix ")")
  519.     (write (pprint-pop))
  520.     (pprint-exit-if-list-exhausted)
  521.     (write-char #\space)
  522.     (pprint-logical-block (nil (pprint-pop) :prefix "(" :suffix ")")
  523.       (pprint-exit-if-list-exhausted)
  524.       (loop (pprint-logical-block (nil (pprint-pop) :prefix "(" :suffix ")")
  525.           (pprint-exit-if-list-exhausted)
  526.           (loop (write (pprint-pop))
  527.             (pprint-exit-if-list-exhausted)
  528.             (write-char #\space)
  529.             (pprint-newline :linear)))
  530.         (pprint-exit-if-list-exhausted)
  531.         (write-char #\space)
  532.         (pprint-newline :fill)))
  533.     (pprint-indent :block 1)
  534.     (loop (pprint-exit-if-list-exhausted)
  535.       (write-char #\space)
  536.       (pprint-newline :linear)
  537.       (write (pprint-pop)))))
  538.  
  539. Suppose that one evaluates the following with *PRINT-LEVEL* 4, and
  540. *PRINT-CIRCLE* T.
  541.  
  542. (pprint-let *standard-output*
  543.         '#1=(let (x (*print-length* (f (g 3))) 
  544.               (z . 2) (k (car y)))
  545.           (setq x (sqrt z)) #1#))
  546.  
  547. If the line length is greater than or equal to 77, the output produced
  548. appears on one line.  However, if the line length is 76, line breaks are
  549. inserted at the linear-style conditional newlines separating the forms in
  550. the body and the output below is produced.  Note that, the degenerate
  551. binding pair X is printed readably even though it fails to be a list; a
  552. depth abbreviation marker is printed in place of (G 3); the binding pair
  553. (Z . 2) is printed readably even though it is not a proper list; and
  554. appropriate circularity markers are printed.
  555.  
  556. #1=(LET (X (*PRINT-LENGTH* (F #)) (Z . 2) (K (CAR Y))) 
  557.      (SETQ X (SQRT Z))
  558.      #1#)
  559.  
  560. If the line length is reduced to 35, a line break is inserted at one of the
  561. fill-style conditional newlines separating the binding pairs.
  562.  
  563. #1=(LET (X (*PRINT-PRETTY* (F #))
  564.          (Z . 2) (K (CAR Y)))
  565.      (SETQ X (SQRT Z))
  566.      #1#)
  567.  
  568. Suppose that the line length is further reduced to 22 and *PRINT-LENGTH* is
  569. set to 3. In this situation, line breaks are inserted after both the first
  570. and second binding pairs.  In addition, the second binding pair is itself
  571. broken across two lines.  Clause (b) of the description of fill-style
  572. conditional newlines prevents the binding pair (Z . 2) from being printed
  573. at the end of the third line.  Note that the length abbreviation hides the
  574. circularity from view and therefore the printing of circularity markers
  575. disappears.
  576.  
  577. (LET (X
  578.       (*PRINT-LENGTH*
  579.        (F #))
  580.       (Z . 2) ...)
  581.   (SETQ X (SQRT Z))
  582.   ...)
  583.  
  584. ---
  585.  
  586. The function PPRINT-TABULAR could be defined as follows.
  587.  
  588. (defun pprint-tabular (s list &optional (colon? T) atsign? (tabsize nil))
  589.   (declare (ignore atsign?))
  590.   (when (null tabsize) (setq tabsize 16))
  591.   (pprint-logical-block (s list :prefix (if colon? "(" "")
  592.                     :suffix (if colon? ")" ""))
  593.     (pprint-exit-if-list-exhausted)
  594.     (loop (write (pprint-pop) :stream s)
  595.       (pprint-exit-if-list-exhausted)
  596.       (write-char #\space s)
  597.       (pprint-tab :section-relative 0 tabsize s)
  598.       (pprint-newline :fill s))))
  599.  
  600. Evaluating the following with a line length of 25 produces the output shown.
  601.  
  602. (princ "Roads ") 
  603. (pprint-tabular *standard-output* '(elm main maple center) nil nil 8)
  604.  
  605. Roads ELM     MAIN
  606.       MAPLE   CENTER
  607.  
  608. ---
  609.     
  610. The function below prints a vector using #(...) notation.
  611.      
  612. (defun pprint-vector (*standard-output* v)
  613.   (pprint-logical-block (nil nil :prefix "#(" :suffix ")")
  614.     (let ((end (length v)) (i 0))
  615.       (when (plusp end)
  616.     (loop (pprint-pop)
  617.           (write (aref v i))
  618.           (if (= (incf i) end) (return nil))
  619.           (write-char #\space)
  620.           (pprint-newline :fill))))))
  621.  
  622. Evaluating the following with a line length of 15 produces the output shown.
  623.  
  624. (pprint-vector *standard-output* '#(12 34 567 8 9012 34 567 89 0 1 23))
  625.  
  626. #(12 34 567 8 
  627.   9012 34 567 
  628.   89 0 1 23)
  629.  
  630.                      Format Directive Interface
  631.  
  632. The primary interface to operations for dynamically determining the
  633. arrangement of output is provided through the functions above.  However, an
  634. additional interface is provided via a set of new format directives.
  635. This is done, because as shown by the examples in this section and the
  636. next, FORMAT strings are typically a much more compact way to specify
  637. pretty printing.  In addition, without such an interface, one would have to
  638. abandon the use of FORMAT when interacting with the pretty printer.
  639.  
  640. ~W                                                        [format directive]
  641.  
  642. WRITE -- An arg, any Lisp object, is printed obeying every printer control
  643. variable (as by WRITE).  In addition, ~W interacts correctly with depth
  644. abbreviation, by not resetting the depth counter to zero.  ~W does not
  645. accept parameters.  If given the colon modifier, ~W binds *PRINT-PRETTY* to
  646. T.  If given the atsign modifier, ~W binds *PRINT-LEVEL* and *PRINT-LENGTH*
  647. to NIL.
  648.  
  649. ~W provides automatic support for the detection of circularity and
  650. sharing.  If *PRINT-CIRCLE* (and possibly *PRINT-SHARED*) is not NIL
  651. and ~W is applied to an argument that is a circular (or shared)
  652. reference, an appropriate #n# marker is inserted in the output instead
  653. of printing the argument.
  654.  
  655. ~_                                                        [format directive]
  656.  
  657. CONDITIONAL-NEWLINE -- Without any modifiers, ~_ is the same as
  658. (PPRINT-NEWLINE :LINEAR).  ~@_ is the same as (PPRINT-NEWLINE :MISER).
  659. ~:_ is the same as (PPRINT-NEWLINE :FILL).  ~:@_ is the same as
  660. (PPRINT-NEWLINE :MANDATORY).
  661.  
  662. ~<...~:>                                                  [format directive]
  663.  
  664. LOGICAL BLOCK -- If ~:> is used to terminate a ~<...~>, the directive
  665. is equivalent to a call on PPRINT-LOGICAL-BLOCK.  The FORMAT argument
  666. corresponding to the ~<...~:> directive is treated in the same way as
  667. the LIST argument to PPRINT-LOGICAL-BLOCK, thereby providing automatic
  668. support for non-list arguments and the detection of circularity,
  669. sharing, and depth abbreviation.  The portion of the FORMAT control
  670. string nested within the ~<...~:> specifies the :PREFIX (or
  671. :PER-LINE-PREFIX), :suffix}, and body of the PPRINT-LOGICAL-BLOCK.
  672.  
  673. The FORMAT string portion enclosed by ~<...~:> can be divided into
  674. segments ~<prefix~;body~;suffix~:> by ~; directives.  If the first
  675. section is terminated by ~@;, it specifies a per-line prefix rather
  676. than a simple prefix.  The prefix and suffix cannot contain FORMAT
  677. directives.  An error is signalled if either the prefix or suffix
  678. fails to be a constant string or if the enclosed portion is divided
  679. into more than three segments.
  680.  
  681. If the enclosed portion is divided into only two segments, the suffix
  682. defaults to the null string.  If the enclosed portion consists of only
  683. a single segment, both the prefix and the suffix default to the null
  684. string.  If the colon modifier is used (i.e., ~:<...~:>), the prefix
  685. and suffix default to "(" and ")" (respectively) instead of the null
  686. string.
  687.  
  688. The body segment can be any arbitrary FORMAT control string.  This
  689. FORMAT control string is applied to the elements of the list
  690. corresponding to the ~<...~:> directive as a whole.  Elements are
  691. extracted from this list using PPRINT-POP, thereby providing automatic
  692. support for malformed lists, and the detection of circularity,
  693. sharing, and length abbreviation.  Within the body segment, ~^ acts
  694. like PPRINT-EXIT-IF-LIST-EXHAUSTED.
  695.  
  696. ~<...~:> supports a feature not supported by PPRINT-LOGICAL-BLOCK.  If
  697. ~:@> is used to terminate the directive (i.e., ~<...~:@>), then a
  698. fill-style conditional newline is automatically inserted after each
  699. group of blanks immediately contained in the body (except for blanks
  700. after a ~<newline> directive).  This makes it easy to achieve the
  701. equivalent of paragraph filling.
  702.  
  703. If the atsign modifier is used with ~<...~:>, the entire remaining
  704. argument list is passed to the directive as its argument.  All of the
  705. remaining arguments are always consumed by ~@<...~:>, even if they are
  706. not all used by the FORMAT string nested in the directive.  Other than
  707. the difference in its argument, ~@<...~:> is exactly the same as
  708. ~<...~:> except that " . #n#" is printed if circularity or sharing has
  709. to be indicated for its argument as a whole.
  710.  
  711. To a considerable extent, the basic form of the directive ~<...~> is
  712. incompatible with the dynamic control of the arrangement of output by
  713. ~W, ~_, ~<...~:>, ~I, and ~:T.  As a result, an error is signalled if
  714. any of these directives is nested within ~<...~>.  Beyond this, an
  715. error is also signalled if the ~<...~:;...~> form of ~<...~> is used
  716. in the same FORMAT string with ~W, ~_, ~<...~:>, ~I, or ~:T.
  717.  
  718. ~I                                                        [format directive]
  719.  
  720. INDENT -- ~nI is the same as (PPRINT-INDENT :BLOCK N).
  721. ~n:I is the same as (PPRINT-INDENT :CURRENT N).  In both cases, N defaults
  722. to zero, if it is omitted.
  723.  
  724. ~:T                                                       [format directive]
  725.  
  726. TABULATE -- If the colon modifier is used with the ~T directive, the
  727. tabbing computation is done relative to the horizontal position where the
  728. section immediately containing the directive begins, rather than with
  729. respect to a horizontal position of zero.  The numerical parameters are
  730. both interpreted as being in units of ems and both default to 1.
  731. ~n,m:T is the same as (PPRINT-TAB :SECTION N M).
  732. ~n,m:@T is the same as (PPRINT-TAB :SECTION-RELATIVE N M).
  733.  
  734. ~/name/                                                   [format directive]
  735.  
  736. CALL FUNCTION -- User defined functions can be called from within a FORMAT
  737. string by using the directive ~/name/.  The colon modifier, the atsign
  738. modifier, and arbitrarily many parameters can be specified with the ~/name/
  739. directive.  NAME can be any arbitrary string that does not contain a "/".
  740. All of the characters in NAME are treated as if they were upper case.  If
  741. NAME contains a ":" or "::", then everything up to but not including the
  742. first ":" or "::" is taken to be a string that names a package.  Everything
  743. after the first ":" or "::" (if any) is taken to be a string that names a
  744. symbol.  The function corresponding to a ~/name/ directive is obtained by
  745. looking up the symbol that has the indicated name in the indicated package.
  746. If NAME does not contain a ":" or "::", then the whole name string is
  747. looked up in the USER package.
  748.  
  749. When a ~/name/ directive is encountered, the indicated function is called
  750. with four or more arguments.  The first four arguments are: the output
  751. stream, the FORMAT argument corresponding to the directive, the value T if
  752. the colon modifier was used (NIL otherwise), and the value T if the atsign
  753. modifier was used (NIL otherwise).  The remaining arguments consist of any
  754. parameters specified with the directive.  The function should print the
  755. argument appropriately.  Any values returned by the function are ignored.
  756.  
  757. The three functions PPRINT-LINEAR, PPRINT-FILL, and PPRINT-TABULAR are
  758. specifically designed so that they can be called by ~/.../ (i.e.,
  759. ~/PPRINT-LINEAR/, ~/PPRINT-FILL/, and ~/PPRINT-TABULAR/).  In particular
  760. they take colon and atsign arguments.
  761.  
  762. ---
  763.  
  764. As examples of the convenience of specifying pretty printing with FORMAT
  765. strings, consider that the first two functions used as examples in the last
  766. section can be compactly defined as follows.  The function PPRINT-VECTOR
  767. cannot be defined using FORMAT, because the data structure it traverses is
  768. not a list.  The function PPRINT-TABULAR is inconvenient to define using
  769. FORMAT, because of the need to pass its TABSIZE argument through to a ~:T
  770. directive nested within an iteration over a list.
  771.  
  772. (defun simple-pprint-defun (*standard-output* list)
  773.   (format T "~:<~W ~@_~:I~W ~:_~W~1I ~_~W~:>" list))
  774.  
  775. (defun pprint-let (*standard-output* list)
  776.   (format T "~:<~W~^ ~:<~@{~:<~@{~W~^ ~_~}~:>~^ ~:_~}~:>~1I~@{~^ ~_~W~}~:>" list)) 
  777.  
  778.            Compiling Format Control Strings
  779.  
  780. The control strings used by FORMAT are essentially programs that perform
  781. printing.  The macro FORMATTER provides the efficiency of using a compiled
  782. function for printing without losing the compactness of FORMAT control
  783. strings.
  784.  
  785. FORMATTER control-string                                           [macro]
  786.  
  787. CONTROL-STRING must be a literal string.  An error is signalled if
  788. CONTROL-STRING is not a valid FORMAT control string.  The macro FORMATTER
  789. expands into an expression of the form (FUNCTION (LAMBDA (STREAM &REST
  790. ARGS) ...))  that does the printing specified by CONTROL-STRING.  The
  791. LAMBDA created accepts an output stream as its first argument and zero or
  792. more data values as its remaining arguments.  The value returned by the
  793. LAMBDA is the tail (if any) of the data values that are not printed out by
  794. CONTROL-STRING.  (E.g., if the CONTROL-STRING is "~A~A" the CDDR (if any)
  795. of the data values is returned.)
  796.  
  797. For instance: (formatter "~%~2@{~S, ~}") is equivalent to
  798.  
  799. #'(lambda (stream &rest args)
  800.     (terpri stream)
  801.     (dotimes (n 2)
  802.       (if (null args) (return nil))
  803.       (prin1 (pop args) stream)
  804.       (write-string ", " stream))
  805.     args)
  806.  
  807. In support of the above, FORMAT is extended so that it accepts functions as
  808. its second argument as well as strings.  When a function is provided, it
  809. must be a function of the form created by FORMATTER.  The function is called
  810. with the appropriate output stream as its first argument and the data
  811. arguments to FORMAT as its remaining arguments.  The function should
  812. perform whatever output is necessary and return the unused tail of the
  813. arguments (if any).  The directives ~? and ~{~} with no body are also
  814. extended so that they accept functions as well as control strings.
  815. Every other standard function that takes a FORMAT string as an argument
  816. (e.g., ERROR and WARN) are also extended so that they can accept functions
  817. of the form above instead.
  818.  
  819.             Pretty Print Dispatch Tables
  820.  
  821. When *PRINT-PRETTY* is not NIL, the pprint dispatch table in the variable
  822. *PRINT-PPRINT-DISPATCH* controls how objects are printed.  The information
  823. in this table takes precedence over all other mechanisms for specifying how
  824. to print objects.  In particular, it overrides user-defined PRINT-OBJECT
  825. methods and print functions for structures.  However, if there is no
  826. specification for how to pretty print a particular kind of object, it is then
  827. printed using the standard mechanisms as if *PRINT-PRETTY* were NIL.
  828.  
  829. Pprint dispatch tables are mappings from keys to pairs of values.  The keys
  830. are type specifiers.  The values are functions and numerical priorities.
  831. Basic insertion and retrieval is done based on the keys with the equality
  832. of keys being tested by EQUAL.  The function to use when pretty printing an
  833. object is chosen by finding the highest priority function from
  834. *PRINT-PPRINT-DISPATCH* that is associated with a type specifier that
  835. matches the object.
  836.  
  837.  
  838. COPY-PPRINT-DISPATCH &optional (table *PRINT-PPRINT-DISPATCH*)    [function]
  839.  
  840. A copy is made of TABLE, which defaults to the current pprint dispatch
  841. table.  If TABLE is NIL, a copy is returned of the initial value of
  842. *PRINT-PPRINT-DISPATCH*.
  843.  
  844.  
  845. PPRINT-DISPATCH object &optional (table *PRINT-PPRINT-DISPATCH*)   [function] 
  846.  
  847. This retrieves the highest priority function from a pprint table that is
  848. associated with a type specifier in the table that matches OBJECT.  The
  849. function is chosen by finding all the type specifiers in TABLE that match
  850. the object and selecting the highest priority function associated with any
  851. of these type specifiers.  If there is more than one highest priority
  852. function, an arbitrary choice is made.  If no type specifiers match the
  853. object, a function is returned that prints object with *PRINT-PRETTY* bound
  854. to NIL.
  855.  
  856. As a second return value, PPRINT-DISPATCH returns a flag that is T if a
  857. matching type specifier was found in TABLE and NIL if not.
  858.  
  859. TABLE (which defaults to *PRINT-PPRINT-DISPATCH*) must be a pprint dispatch
  860. table.  TABLE can be NIL, in which case retrieval is done in the initial
  861. value of *PRINT-PPRINT-DISPATCH*.
  862.  
  863. When *PRINT-PRETTY* is T, (WRITE OBJECT :STREAM S) is equivalent to
  864. (FUNCALL (PPRINT-DISPATCH OBJECT) S OBJECT).
  865.  
  866.  
  867. SET-PPRINT-DISPATCH type-specifier function                        [function]
  868.                     &optional (priority 0) (table *PRINT-PPRINT-DISPATCH*)
  869.  
  870. This puts an entry into a pprint dispatch table and returns NIL.
  871. TYPE-SPECIFIER must be a valid type specifier and is the key of the entry.
  872. The first action of SET-PPRINT-DISPATCH is to remove any pre-existing entry
  873. associated with TYPE-SPECIFIER.  This guarantees that there will never be
  874. two entries associated with the same type specifier in a given pprint
  875. dispatch table.  Equality of type specifiers is tested by EQUAL.
  876.  
  877. Two values are associated with each type specifier in a pprint dispatch
  878. table: a function and a priority.  FUNCTION must accept two arguments: the
  879. stream to send output to and the object to be printed.  FUNCTION should
  880. pretty print the object on the stream.  FUNCTION can assume that object
  881. satisfies TYPE-SPECIFIER.  Function must obey *PRINT-READABLY* (see issue
  882. DATA-IO).  Any values returned by FUNCTION are ignored.
  883.  
  884. PRIORITY (which defaults to 0) must be a non-complex number.  This
  885. number is used as a priority to resolve conflicts when an object
  886. matches more than one entry.  An error is signalled if priority fails
  887. to be a non-complex number.
  888.  
  889. TABLE (which defaults to *PRINT-PPRINT-DISPATCH*) must be a pprint dispatch
  890. table.  The specified entry is placed in this table.
  891.  
  892. It is permissible for FUNCTION to be NIL.  In this situation, there will be
  893. no TYPE-SPECIFIER entry in TABLE after SET-PPRINT-DISPATCH is evaluated.
  894.  
  895. To facilitate the use of pprint dispatch tables for controlling the pretty
  896. printing of Lisp code, the TYPE-SPECIFIER argument of the function
  897. SET-PPRINT-DISPATCH is allowed to contain constructs of the form 
  898.  
  899.            (CONS car-type cdr-type)
  900.  
  901. This signifies that the corresponding object must be a cons cell whose car
  902. matches the type specifier CAR-TYPE and whose cdr matches the type specifier
  903. CDR-TYPE.  The CDR-TYPE can be omitted in which case it defaults to T.
  904.  
  905.  
  906. The initial value of *PRINT-PPRINT-DISPATCH* is implementation dependent.
  907. However, the initial entries all use a special class of priorities that
  908. have the property that they are less than every priority that can be
  909. specified using SET-PPRINT-DISPATCH.  The benefit of this is that it
  910. guarantees that any pretty printing functions users specify will override
  911. everything in the initial value of *PRINT-PPRINT-DISPATCH*.
  912.  
  913. ----------------------------------------------------------------------
  914.  
  915. Implementation note:  The restriction above is very useful to users
  916. without actually limiting what Common Lisp implementors can do.  It is
  917. possible for implementors to set up any kind of pretty printing they
  918. desire using the range of priorities available to them.
  919.  
  920. ----------------------------------------------------------------------
  921.  
  922.  
  923. Consider the following examples.  The first form restores
  924. *PRINT-PPRINT-DISPATCH* to its initial value.  The next two forms then set
  925. up a special way to pretty print ratios.  Note that the more specific type
  926. specifier has to be associated with a higher priority.
  927.  
  928. (setq *print-pprint-dispatch* (copy-pprint-dispatch nil))
  929.  
  930. (set-pprint-dispatch 'ratio
  931.   #'(lambda (s obj)
  932.       (format s "#.(/ ~W ~W)" (numerator obj) (denominator obj))))
  933.  
  934. (set-pprint-dispatch '(and ratio (satisfies minusp))
  935.   #'(lambda (s obj)
  936.       (format s "#.(- (/ ~W ~W))" (- (numerator obj)) (denominator obj)))
  937.   5)
  938.  
  939. (pprint '(1/3 -2/3)) prints: (#.(/ 1 3) #.(- (/ 2 3)))
  940.  
  941. The following two forms illustrate the definition of pretty printing
  942. functions for types of Lisp code.  The first form illustrates how to
  943. specify the traditional method for printing quoted objects using "'"
  944. syntax.  Note the care taken to ensure that data lists that happen to begin
  945. with QUOTE will be printed readably.  The second form specifies that lists
  946. beginning with the symbol MY-LET should print the same way that lists
  947. beginning with LET print when the initial pprint dispatch table is in effect.
  948.  
  949. (set-pprint-dispatch '(cons (member quote)) () 
  950.   #'(lambda (s list)
  951.       (if (and (consp (cdr list)) (null (cddr list)))
  952.       (funcall (formatter "'~W") s (cadr list))
  953.       (pprint-fill s list)))))
  954.  
  955. (set-pprint-dispatch '(cons (member my-let)) (pprint-dispatch '(let) nil))
  956.  
  957. The next example specifies a default method for printing lists that do not
  958. correspond to function calls.  Note that, as shown in the definition of
  959. PPRINT-TABULAR above, PPRINT-LINEAR, PPRINT-FILL, and PPRINT-TABULAR are
  960. all defined with optional COLON? and ATSIGN? arguments so that they can be
  961. used as pprint dispatch functions as well as ~/.../ functions.
  962.  
  963. (set-pprint-dispatch '(cons (not (and symbol (satisfies fboundp))))
  964.                      #'pprint-fill -5)
  965.  
  966. with a line length of 9, (pprint '(0 b c d e f g h i j k)) prints: 
  967. (0 b c d
  968.  e f g h
  969.  i j k)
  970.  
  971. This final example shows how to define a pretty printing function for a
  972. user defined data structure.
  973.  
  974. (defstruct family mom kids)
  975.  
  976. (set-pprint-dispatch 'family
  977.   #'(lambda (s f)
  978.       (funcall (formatter "~@<#<~;~W and ~2I~_~/pprint-fill/~;>~:>")
  979.            s (family-mom f) (family-kids f))))
  980.  
  981. The pretty printing function for the structure FAMILY specifies how to
  982. adjust the layout of the output so that it can fit aesthetically into
  983. a variety of line widths.  In addition, it obeys the printer control
  984. variables *PRINT-LEVEL*, *PRINT-LENGTH*, *PRINT-LINES*,
  985. *PRINT-CIRCLE*, *PRINT-SHARED* and *PRINT-ESCAPE*, and can tolerate
  986. several different kinds of malformity in the data structure.  The
  987. output below shows what is printed out with a right margin of 25,
  988. *PRINT-PRETTY* T, *PRINT-ESCAPE* NIL, and a malformed KIDS list.
  989.  
  990. (write (list 'principal-family
  991.              (make-family :mom "Lucy"
  992.                           :kids '("Mark" "Bob" . "Dan")))
  993.        :right-margin 25 :pretty T :escape nil :miser-width nil)
  994.  
  995. (PRINCIPAL-FAMILY
  996.  #<Lucy and
  997.      Mark Bob . Dan>)
  998.  
  999. Note that a pretty printing function for a structure is different from the
  1000. structure's print function.  While print functions are permanently
  1001. associated with a structure, pretty printing functions are stored in pprint
  1002. dispatch tables and can be rapidly changed to reflect different printing
  1003. needs.  If there is no pretty printing function for a structure in the
  1004. current print dispatch table, the print function (if any) is used instead.
  1005.  
  1006. ;------------------------------------------------------------------------
  1007.  
  1008. ;Copyright 1989 by the Massachusetts Institute of Technology, Cambridge, 
  1009. ;Massachusetts.
  1010.  
  1011. ;Permission to use, copy, modify, and distribute this software and its
  1012. ;documentation for any purpose and without fee is hereby granted,
  1013. ;provided that this copyright and permission notice appear in all
  1014. ;copies and supporting documentation, and that the name of M.I.T. not
  1015. ;be used in advertising or publicity pertaining to distribution of the
  1016. ;software without specific, written prior permission. M.I.T. makes no
  1017. ;representations about the suitability of this software for any
  1018. ;purpose.  It is provided "as is" without express or implied warranty.
  1019.  
  1020. ;    M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  1021. ;    ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
  1022. ;    M.I.T. BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  1023. ;    ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  1024. ;    WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
  1025. ;    ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  1026. ;    SOFTWARE.
  1027.  
  1028. ;------------------------------------------------------------------------
  1029.